﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace ChoMy.Helpers
{
    public class FileHelper
    {
        public string Valid(HttpPostedFileBase file)
        {
            if (file == null || file.ContentLength == 0)
            {
                return "Unvalid";
            }

            return "";
        }

        public string Upload(HttpPostedFileBase file, string name, string local)
        {
            var directory = new DirectoryInfo(HttpContext.Current.Server.MapPath(local));

            if (directory.Exists == false)
            {
                directory.Create();
            }

            string uName = new StringHelper().Unsigned(name);

            string ext = Path.GetExtension(file.FileName);

            string url = local + uName + "-" + Path.GetRandomFileName().Replace(".", "") + ext;

            string path = HttpContext.Current.Server.MapPath(url);

            file.SaveAs(path);

            return url;
        }

        public void Rename(string oldUrl, string newUrl)
        {
            var oldPath = HttpContext.Current.Server.MapPath(oldUrl);
            var newPath = HttpContext.Current.Server.MapPath(newUrl);

            if (File.Exists(oldPath))
            {
                File.Move(oldPath, newPath);
            }
        }

        public void Delete(string url)
        {
            var path = HttpContext.Current.Server.MapPath(url);

            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }
    }
}